package cn.iocoder.yudao.module.member.user.controller.admin;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.business.basic.pojo.vo.UserSimpleVO;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.region.RegionUtils;
import cn.iocoder.yudao.framework.region.enums.RegionDataSet;
import cn.iocoder.yudao.module.api.member.point.enums.MemberPointBizTypeEnum;
import cn.iocoder.yudao.module.api.pay.bill.PayBillApi;
import cn.iocoder.yudao.module.api.pay.bill.dto.PayBillCreateDTO;
import cn.iocoder.yudao.module.api.pay.bill.enums.BillCategoryEnum;
import cn.iocoder.yudao.module.api.pay.bill.enums.BillTypeEnum;
import cn.iocoder.yudao.module.member.assets.service.AppMemberDigitalAssetsService;
import cn.iocoder.yudao.module.member.level.service.MemberLevelService;
import cn.iocoder.yudao.module.member.point.service.MemberPointRecordService;
import cn.iocoder.yudao.module.member.tag.service.MemberTagService;
import cn.iocoder.yudao.module.member.user.convert.UserConvert;
import cn.iocoder.yudao.module.member.user.dal.dataobject.MemberUserDO;
import cn.iocoder.yudao.module.member.user.service.MemberUserService;
import cn.iocoder.yudao.module.member.user.vo.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils.getLoginUserId;

@Tag(name = "管理后台 - 前台用户")
@RestController
@RequestMapping("/member/user")
@Validated
public class MemberUserController {

    @Resource
    private MemberUserService memberUserService;
    @Resource
    private MemberTagService memberTagService;
    @Resource
    private MemberLevelService memberLevelService;
    @Resource
    private MemberPointRecordService memberPointRecordService;
    @Resource
    private AppMemberDigitalAssetsService appMemberDigitalAssetsService;

    @Resource
    private PayBillApi payBillApi;

    @PutMapping("/update")
    @Operation(summary = "更新前台用户")
    @PreAuthorize("@ss.hasPermission('member:user:update')")
    public CommonResult<Boolean> updateUser(@Valid @RequestBody MemberUserUpdateReqVO updateReqVO) {
        memberUserService.updateUser(updateReqVO);
        return success(true);
    }

    @PutMapping("/update-level")
    @Operation(summary = "更新用户等级")
    @PreAuthorize("@ss.hasPermission('member:user:update-level')")
    public CommonResult<Boolean> updateUserLevel(@Valid @RequestBody MemberUserUpdateLevelReqVO updateReqVO) {
        memberLevelService.updateUserLevel(updateReqVO);
        return success(true);
    }

    @PutMapping("/update-point")
    @Operation(summary = "更新前台用户积分")
    @PreAuthorize("@ss.hasPermission('member:user:update-point')")
    public CommonResult<Boolean> updateUserPoint(@Valid @RequestBody MemberUserUpdatePointReqVO updateReqVO) {
        memberPointRecordService.createPointRecord(updateReqVO.getId(), updateReqVO.getPoint(),
                MemberPointBizTypeEnum.ADMIN, String.valueOf(getLoginUserId()));
        return success(true);
    }

    @PutMapping("/update-cryptocurrency")
    @Operation(summary = "更新前台用户联盟豆")
    @PreAuthorize("@ss.hasPermission('member:user:update-point')")
    public CommonResult<Boolean> updateUserCryptocurrency(@Valid @RequestBody MemberUserUpdateCryptocurrencyReqVO updateReqVO) {
        appMemberDigitalAssetsService.changeCryptocurrencyOrigin(updateReqVO.getId(), updateReqVO.getCryptocurrency());
        if (updateReqVO.getCryptocurrency() > 0) {
            payBillApi.incomeAsync(new PayBillCreateDTO()
                    .setUserId(updateReqVO.getId())
                    .setCategory(BillCategoryEnum.CRYPTOCURRENCY_ORIGIN)
                    .setType(BillTypeEnum.SYSTEM_ADJUST)
                    .setNumber(updateReqVO.getCryptocurrency())
                    .setMark("管理员【ID#%s】手动增加【%s个】联盟豆".formatted(getLoginUserId(), updateReqVO.getCryptocurrency()))
                    .setRelateId(String.valueOf(getLoginUserId()))
                    .setExtendField(""));
        } else {
            payBillApi.expendAsync(new PayBillCreateDTO()
                    .setUserId(updateReqVO.getId())
                    .setCategory(BillCategoryEnum.CRYPTOCURRENCY_ORIGIN)
                    .setType(BillTypeEnum.SYSTEM_ADJUST)
                    .setNumber(updateReqVO.getCryptocurrency())
                    .setMark("管理员【ID#%s】手动扣减【%s个】联盟豆".formatted(getLoginUserId(), Math.abs(updateReqVO.getCryptocurrency())))
                    .setRelateId(String.valueOf(getLoginUserId()))
                    .setExtendField(""));

        }
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得前台用户")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('member:user:query')")
    public CommonResult<MemberUserRespVO> getUser(@RequestParam("id") Long id) {
        MemberUserDO user = memberUserService.getUser(id);
        if (user == null) {
            return success(null);
        }
        MemberUserRespVO data = UserConvert.INSTANCE.convertIncludeRegion(user);
        RegionUtils.autoAssignCounty(RegionDataSet.ONLY_LATEST, data.getCountyCode(), data);
        return success(data);
    }

    @GetMapping("/page")
    @Operation(summary = "获得前台用户分页")
    @PreAuthorize("@ss.hasPermission('member:user:query')")
    public CommonResult<PageResult<MemberUserRespVO>> getUserPageV2(@Valid MemberUserPageReqVO pageVO) {
        PageResult<MemberUserDO> pageResult = memberUserService.getUserPage(pageVO);
        List<MemberUserDO> list = pageResult.getList();
        if (CollUtil.isEmpty(list)) {
            return CommonResult.success(PageResult.empty());
        }
        // 处理用户标签返显
        Map<Long, String> tagMap = memberTagService.getTagMap(list.stream()
                .map(MemberUserDO::getTagIds)
                .filter(Objects::nonNull)
                .flatMap(Collection::stream)
                .collect(Collectors.toSet()));
        // 处理用户级别返显
        Map<Long, String> levelMap = memberLevelService.getLevelMap(convertSet(list, MemberUserDO::getLevelId));
        PageResult<MemberUserRespVO> data = BeanUtils.toBean(pageResult, MemberUserRespVO.class);
        // 填充关联数据
        data.getList().forEach(item -> {
            item.setTagNames(CollectionUtils.convertList(item.getTagIds(), tagMap::get));
            item.setLevelName(levelMap.get(item.getLevelId()));
            RegionUtils.autoAssignCounty(RegionDataSet.ONLY_LATEST, item.getCountyCode(), item);
        });
        return CommonResult.success(data);
    }

    @GetMapping("/pick")
    @Operation(summary = "获得前台用户分页（用于选择用户）")
    @PreAuthorize("@ss.hasAnyRoles('super_admin', 'platform_admin', 'tenant_admin', 'shop_admin')")
    public CommonResult<List<UserSimpleVO>> getUserPageForPick(@Valid MemberUserPickReqVO reqVO) {
        List<MemberUserDO> list = memberUserService.getUserList(reqVO);
        return CommonResult.success(BeanUtils.toBean(list, UserSimpleVO.class));
    }

    @GetMapping("/robot-list")
    @Operation(summary = "获得机器人列表")
    @PreAuthorize("@ss.hasPermission('member:user:query')")
    public CommonResult<List<MemberUserRespVO>> getRobotList() {
        List<MemberUserDO> list = memberUserService.getRobotList();
        if (CollUtil.isEmpty(list)) {
            return CommonResult.success(Collections.emptyList());
        }
        List<MemberUserRespVO> data = BeanUtils.toBean(list, MemberUserRespVO.class);
        data.forEach(item -> RegionUtils.autoAssignCounty(RegionDataSet.ONLY_LATEST, item.getCountyCode(), item));
        return CommonResult.success(data);
    }

}
